import { computed, onUnmounted, ref } from "vue"
import dayjs from "dayjs"
export const useCountDown = () => {
    const time = ref(0)
    const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
    let timer = null
    // 传入倒计时的秒数
    const start = (currentTime) => {
        time.value = currentTime
        timer = setInterval(() => {
            if (time.value > 0) {
                time.value --
            } else {
                timer && clearTimeout(timer)
            }
        }, 1000)
    }
    
    // 组件销毁时清除定时器
    onUnmounted(() => {
        timer && clearTimeout(timer)
    })
    return {
        formatTime,
        start
    }
} 